import 'dart:async';
import 'dart:io';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';

class PreviewFile extends StatefulWidget {
  final String fileUrl;

  const PreviewFile({super.key, required this.fileUrl});

  @override
  State<PreviewFile> createState() => _Content();
}

class _Content extends State<PreviewFile> {
  String remotePDFPath = "";
  final Completer<PDFViewController> _controller =
      Completer<PDFViewController>();
  int? pages = 0;
  int? currentPage = 0;
  bool isReady = false;
  String errorMessage = '';

  @override
  void initState() {
    super.initState();
    createFileOfPdfUrl().then((f) {
      setState(() {
        remotePDFPath = f.path;
        debugPrint('remotePDFPath-----------------------$remotePDFPath');
      });
    });
  }

  Future<File> createFileOfPdfUrl() async {
    Completer<File> completer = Completer();
    try {
      String url = widget.fileUrl;
      final filename = url.substring(url.lastIndexOf("/") + 1);
      var request = await HttpClient().getUrl(Uri.parse(url));
      var response = await request.close();
      var bytes = await consolidateHttpClientResponseBytes(response);
      var dir = await getApplicationDocumentsDirectory();

      File file = File("${dir.path}/$filename");
      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file!');
    }

    return completer.future;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('文件预览', style: TextStyle(color: Colors.white, fontSize: 16)),
        toolbarHeight: 40,
        backgroundColor: Colors.deepPurple[300],
        centerTitle: true,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      body: _preview(),
      floatingActionButton: FutureBuilder<PDFViewController>(
        future: _controller.future,
        builder: (context, AsyncSnapshot<PDFViewController> snapshot) {
          if (snapshot.hasData) {
            return FloatingActionButton.extended(
              label: const Text("首页"),
              onPressed: () async {
                await snapshot.data!.setPage(0);
              },
            );
          }
          return Container();
        },
      ),
    );
  }

  Widget _preview() {
    if (remotePDFPath.isEmpty) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          SpinKitCircle(
            color: Colors.deepPurple[300],
            size: 50.0,
          ),
          const SizedBox(height: 16.0), // 添加一些间距
          Text(
            '加载中...',
            style: TextStyle(fontSize: 16.0, color: Colors.deepPurple[300]), // 根据需要调整样式
          ),
        ],
      );
    }
    return SizedBox(
      width: double.infinity,
      height: double.infinity,
      child:  Stack(
        children: <Widget>[
          PDFView(
            filePath: remotePDFPath,
            enableSwipe: true,
            swipeHorizontal: true,
            autoSpacing: false,
            pageFling: true,
            pageSnap: true,
            defaultPage: currentPage!,
            fitPolicy: FitPolicy.BOTH,
            preventLinkNavigation: false,
            backgroundColor: Colors.black,
            onRender: (page) {
              setState(() {
                pages = page;
                isReady = true;
              });
            },
            onError: (error) {
              setState(() {
                errorMessage = error.toString();
              });
              debugPrint(error.toString());
            },
            onPageError: (page, error) {
              setState(() {
                errorMessage = '$page: ${error.toString()}';
              });
              debugPrint('$page: ${error.toString()}');
            },
            onViewCreated: (PDFViewController pdfViewController) {
              _controller.complete(pdfViewController);
            },
            onLinkHandler: (String? uri) {
              debugPrint('goto uri: $uri');
            },
            onPageChanged: (int? page, int? total) {
              debugPrint('page change: $page');
              setState(() {
                currentPage = page;
              });
            },
          ),
          errorMessage.isEmpty
              ? !isReady
              ? const Center(child: CircularProgressIndicator())
              : Container()
              : Center(child: Text(errorMessage))
        ],
      )
    );
  }
}
